package com.easonji.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.easonji.admin.form.PermissionForm;
import com.easonji.admin.mapper.PermissionMapper;
import com.easonji.admin.model.RolePermission;
import com.easonji.admin.query.PermissionQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.easonji.admin.dao.PermissionDAO;
import com.easonji.admin.manager.AppManager;
import com.easonji.admin.manager.PermissionManager;
import com.easonji.admin.mapper.RolePermissionMapper;
import com.easonji.admin.model.Permission;
import com.easonji.admin.service.PermissionService;
import com.easonji.common.base.service.AbstractBaseService;
import com.easonji.common.constant.cache.CacheConsts;
import com.easonji.common.constant.cache.CacheKeyConsts;
import com.easonji.common.constant.enums.IsMenuEnum;
import com.easonji.common.util.JsonUtils;
import com.easonji.common.util.StringUtils;
import com.easonji.core.annotion.CacheRemove;
import com.easonji.core.exception.BizException;

/**
 * @ClassName: PermissionService
 * @Description: 权限服务实现类
 * @Author: LiuJun
 * @date: 2018/07/30 14:07:16
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Service
public class PermissionServiceImpl extends AbstractBaseService<Permission> implements PermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private PermissionDAO permissionDAO;

    @Resource
    private PermissionManager permissionManager;

    @Resource
    private AppManager aapManager;

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public Object queryPermissionList(PermissionQuery permissionQuery) {
        // 查询条件
        Wrapper<Permission> wrapper = new EntityWrapper<>();
        Integer appId = permissionQuery.getAppId();
        if (StringUtils.isEmpty(appId)) {
            wrapper.eq("app_id", 1);
        } else {
            wrapper.eq("app_id", appId);
        }
        String condition = permissionQuery.getCondition();
        if (StringUtils.isNotEmpty(condition)) {
            wrapper.like("name", condition);
        }
        // 排序
        List<String> columns = new ArrayList<>();
        columns.add("parent_id");
        columns.add("num");
        wrapper.orderAsc(columns);
        List<Permission> permissions = permissionMapper.selectList(wrapper);
        return warp(permissions);
    }

    @Override
    public Object queryPermission(Integer permissionId) {
        Permission permission = permissionMapper.selectById(permissionId);
        JSONObject result = JsonUtils.parseObject(permission);
        result.put("isMenuName", IsMenuEnum.valueOf(permission.getIsMenu()));
        result.put("appName", aapManager.getAppNameById(permission.getAppId()));
        result.put("parentName", permissionManager.getPermissionNameById(permission.getParentId()));
        return result;
    }

    @Override
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.PERMISSION })
    public Integer savePermission(PermissionForm permissionForm) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionForm, permission);
        permissionSetAllParentId(permission);
        return permissionMapper.insert(permission);
    }

    @Override
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.PERMISSION })
    public Integer updatePermission(PermissionForm permissionForm) {
        Permission permission = new Permission();
        BeanUtils.copyProperties(permissionForm, permission);
        permissionSetAllParentId(permission);
        return permissionMapper.updateById(permission);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = BizException.class)
    @CacheRemove(value = CacheConsts.CONSTS, key = { CacheKeyConsts.PERMISSION })
    public void removePermission(Integer permissionId) {
        Permission permission = permissionMapper.selectById(permissionId);
        // 查询子权限
        Wrapper<Permission> wrapper = new EntityWrapper<>();
        wrapper.eq("id", permissionId).or().like("all_parent_id", "[" + permission.getId() + "]");
        List<Permission> permissions = permissionMapper.selectList(wrapper);
        // 获取权限ID
        List<Integer> ids = new ArrayList<>();
        permissions.forEach(p -> {
            ids.add(p.getId());
        });
        // 删除所有角色权限
        Wrapper<RolePermission> rpWrapper = new EntityWrapper<>();
        rpWrapper.in("permission_id", ids);
        rolePermissionMapper.delete(rpWrapper);
        // 删除子权限
        permission.delete(wrapper);
    }

    @Override
    protected JSONObject warp2Json(Permission permission) {
        JSONObject result = JsonUtils.parseObject(permission);
        result.put("isMenuName", IsMenuEnum.valueOf(permission.getIsMenu()));
        result.put("appName", aapManager.getAppNameById(permission.getAppId()));
        return result;
    }

    /**
     * 根据父权限ID，设置全部父权限ID
     * 
     * @param dept
     *            部门信息
     */
    private void permissionSetAllParentId(Permission permission) {
        int paretntId = permission.getParentId();
        if (StringUtils.isEmpty(paretntId) || paretntId == 0) {
            permission.setAllParentId("[0],");
        } else {
            Permission parentPermission = permissionMapper.selectById(paretntId);
            if (StringUtils.isNotEmpty(parentPermission) && StringUtils.isNotEmpty(parentPermission.getAllParentId())) {
                permission.setAllParentId(parentPermission.getAllParentId() + "[" + paretntId + "],");
            }
        }
    }
}
